package com.whfc.base.service.impl;

import com.whfc.base.dao.AppSmsCodeMapper;
import com.whfc.base.entity.AppSmsCode;
import com.whfc.base.manager.SmsMgr;
import com.whfc.base.service.SmsService;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.DateUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Random;

/**
 * @Description:短信服务实现
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/7/27 16:21
 */
@DubboService(interfaceClass = SmsService.class, version = "1.0.0")
public class SmsServiceImpl implements SmsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Random random = new Random();

    @Autowired
    private AppSmsCodeMapper smsCodeMapper;

    @Autowired
    private SmsMgr smsMgr;

    @Override
    public void sendSmsCode(String phone) throws BizException {

        //控制验证码发送频率.
        Date now = new Date();
        AppSmsCode smsCode = smsCodeMapper.selectByPhone(phone);
        if (smsCode != null) {
            Date time = DateUtil.addMinutes(smsCode.getStartTime(), 1);
            if (now.before(time)) {
                throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "短信发送太频繁,请稍后再试");
            }
        }
        //生成验证码
        //String randomNum = "112233" + random.nextInt(9999);
        //String code = randomNum.substring(randomNum.length() - 6);
        String code = RandomStringUtils.randomNumeric(4);
        AppSmsCode newSmsCode = new AppSmsCode();
        newSmsCode.setPhone(phone);
        newSmsCode.setCode(code);
        newSmsCode.setStartTime(now);
        newSmsCode.setEndTime(DateUtil.addMinutes(now, 5));
        smsCodeMapper.insertSelective(newSmsCode);

        logger.info("发送验证码,phone:{},code:{}", phone, code);

        //发送验证码
        smsMgr.SmsApi(phone).sendSmsVerify(phone, code);
    }

    @Override
    public void checkSmsCode(String phone, String code) throws BizException {
        AppSmsCode smsCode = smsCodeMapper.selectByPhoneAndCode(phone, code);
        if (smsCode == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "验证码错误");
        }
        Date now = new Date();
        if (now.after(smsCode.getEndTime())) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "验证码过期");
        }
        smsCode.setState(0);
        smsCodeMapper.updateByPrimaryKeySelective(smsCode);
    }
}
